<script setup lang="ts">
  import { createReusableTemplate } from '@vueuse/core';
  import { useModeModalBinder } from '@/hooks/arco/useModeModalBinder';
  import { useForm } from '@/hooks/arco/useForm';
  import { editServiceInfo } from '@/api/file-management/file';
  import { queryInstInfrastructure } from '@/api/organization/nursing-home';
  import { useSelectOption } from '@/hooks/arco/useSelectOption';
  import { ref, unref } from 'vue';

  const props = withDefaults(
    defineProps<{
      showInModal?: boolean;
    }>(),
    {
      showInModal: true,
    }
  );

  const [DefineTemplate, ReuseTemplate] = createReusableTemplate();

  const form = useForm({
    state: {
      elderId: '',
      staffIds: [],
      staffEcho: [],
      productId: '',
      stockDrawerId: '',
      medicalDrawerId: '',
    },
    rules: {
      staffIds: {
        required: true,
        message: '请选择护理人员',
      },
      productId: {
        required: true,
        message: '请选择长者所用药品柜',
      },
      stockDrawerId: {
        required: true,
        message: '请选择长者所用储药格',
      },
      medicalDrawerId: {
        required: true,
        message: '请选择长者所用配药格',
      },
    },
  });

  const elderSelected = ref({
    productId: '',
    stockDrawerId: '',
    medicalDrawerId: '',
  });

  const isDisabled = (field: string, item: any) => {
    // @ts-ignore
    if (unref(elderSelected)[field] === item.value) {
      return false;
    }

    return item.disabled === 1;
  };

  const editModal = useModeModalBinder({
    modes: ['edit'] as const,
    renderTitle() {
      return '编辑服务';
    },
    onShow(mode, otherParams) {
      form.setFieldsValue(otherParams);
      form.state.elderId = otherParams.elderId;
      form.state.staffIds = otherParams.serviceStaff.map(
        (e: any) => e.serviceStaffId
      );
      form.state.productId = otherParams.medStewardId;
      form.state.stockDrawerId = otherParams.stockDrawerId;
      form.state.medicalDrawerId = otherParams.medicalDrawerId;

      elderSelected.value = {
        productId: otherParams.medStewardId,
        stockDrawerId: otherParams.stockDrawerId,
        medicalDrawerId: otherParams.medicalDrawerId,
      };

      // eslint-disable-next-line no-use-before-define
      medstSelect.retry();
    },
    async onOkClick() {
      await form.validate();
      return editServiceInfo(form.state);
    },
  });

  const medstSelect = useSelectOption({
    name: '长者所用药品柜',
    immediate: !props.showInModal,
    leader: true,
    apiFun: queryInstInfrastructure,
    transformDataFun(data) {
      return data.products;
    },
    fieldNames: {
      label: 'aliasName',
      value: 'productId',
      extra: 'drawers',
    },
    enhanceExtraData: true,
    getValue() {
      return form.state.productId;
    },
  });

  const stockDrawerSelect = useSelectOption({
    name: '长者所用储药格',
    upstream: medstSelect,
    immediate: false,
    apiFun: (e, extra) => {
      if (!extra) return Promise.resolve([]);
      const data = extra.filter((drawer: any) => {
        return drawer.drawerType === 1;
      });
      return Promise.resolve(data);
    },
    getValue() {
      return form.state.stockDrawerId;
    },
    onChange(e) {
      form.state.stockDrawerId = e;
    },
    fieldNames: {
      label: 'drawerSn',
      value: 'drawerId',
      disabled: 'userStatus',
    },
  });

  const medicalDrawerSelect = useSelectOption({
    name: '长者所用配药格',
    upstream: medstSelect,
    immediate: false,
    apiFun: (e, extra: any[]) => {
      if (!extra) return Promise.resolve([]);
      const data = extra.filter((drawer: any) => {
        return drawer.drawerType !== 1;
      });
      return Promise.resolve(data);
    },
    getValue() {
      return form.state.medicalDrawerId;
    },
    onChange(e) {
      form.state.medicalDrawerId = e;
    },
    fieldNames: {
      label: 'drawerSn',
      value: 'drawerId',
      disabled: 'userStatus',
    },
  });

  const staffSelect = useSelectOption({
    name: '服务人员',
    apiFun: queryInstInfrastructure,
    transformDataFun(data) {
      return data.staffs;
    },
    fieldNames: {
      label: 'staffName',
      value: 'staffId',
    },
  });

  defineExpose({
    ...editModal.expose,
    validate: form.validate,
    getData: () => {
      return form.state;
    },
    setData: (data: any) => {
      form.setFieldsValue(data);
    },
  });
</script>

<template>
  <DefineTemplate>
    <a-form
      :layout="showInModal ? 'vertical' : 'horizontal'"
      v-bind="form.bindProps"
    >
      <a-form-item field="staffIds" label="服务人员">
        <!-- <staff-select
          v-model="form.state.staffIds"
          :echo-data="form.state.staffEcho"
          type="checkbox"
          :style="{ width: '100%' }"
          placeholder="请选择"
        /> -->
        <a-select
          v-model="form.state.staffIds"
          multiple
          v-bind="staffSelect.bindProps"
        />
      </a-form-item>

      <a-form-item field="productId" label="药品柜">
        <a-select
          v-model="form.state.productId"
          v-bind="medstSelect.bindProps"
        />
      </a-form-item>

      <a-form-item field="stockDrawerId" label="储药仓">
        <a-select
          v-model="form.state.stockDrawerId"
          v-bind="stockDrawerSelect.bindProps"
          :options="undefined"
        >
          <a-option
            v-for="(item, index) of stockDrawerSelect.bindProps.options"
            :key="index"
            :value="item.value"
            :label="item.label"
            :disabled="isDisabled('stockDrawerId', item)"
            data-info="已分配"
            :class="{
              'option-disabled': true,
              'options-checked': item.value === form.state.stockDrawerId,
            }"
          />
        </a-select>
      </a-form-item>

      <a-form-item field="medicalDrawerId" label="用药仓">
        <a-select
          v-model="form.state.medicalDrawerId"
          v-bind="medicalDrawerSelect.bindProps"
          :options="undefined"
        >
          <a-option
            v-for="(item, index) of medicalDrawerSelect.bindProps.options"
            :key="index"
            :value="item.value"
            :label="item.label"
            :disabled="isDisabled('stockDrawerId', item)"
            data-info="已分配"
            :class="{
              'option-disabled': true,
              'options-checked': item.value === form.state.medicalDrawerId,
            }"
          />
        </a-select>
      </a-form-item>
    </a-form>
  </DefineTemplate>
  <a-drawer
    v-if="showInModal"
    position="right"
    width="400px"
    v-bind="editModal.bindProps"
    class="col"
  >
    <ReuseTemplate />
  </a-drawer>
  <div v-else>
    <ReuseTemplate />
  </div>
</template>

<style lang="less"></style>
